package com.example.android.apis.view;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.View;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {

	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private ChPopupWindow popupWindow;
	private View popupParent;

	public MyItemizedOverlay(Drawable unfocusedBg, Context context) {
		super(boundCenterBottom(unfocusedBg));
	}

	public void addOverlay(OverlayItem overlayItem) {
		mOverlays.add(overlayItem);
		populate();
	}
	public void clear(){
		mOverlays.clear();
		populate();
	}
	
	@Override
	public void draw(Canvas paramCanvas, MapView paramMapView,
			boolean paramBoolean) {
		Projection projection = paramMapView.getProjection();
		
		Paint paint = new Paint();
		paint.setARGB(0x33, 0x00, 0x00, 0x00);
		paint.setStrokeWidth(8);
		if(mOverlays.size() >= 2) {
			OverlayItem startItem = mOverlays.get(0);
			for(int i = 1; i < mOverlays.size(); i++) {
				OverlayItem endItem = mOverlays.get(i);
				Point startPoint = new Point();
				Point endPoint = new Point();
				startPoint = projection.toPixels(startItem.getPoint(), startPoint);
				endPoint = projection.toPixels(endItem.getPoint(), endPoint);
				paramCanvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
				
				startItem = mOverlays.get(i);
			}
		}
		
		super.draw(paramCanvas, paramMapView, paramBoolean);
	}

	public void setPopupWindow(ChPopupWindow popupWindow, View parent) {
		this.popupWindow = popupWindow;
		this.popupParent = parent;
	}
	
	public void removeOverlay(OverlayItem item) {
		mOverlays.remove(item);
		populate();
	}

	@Override
	protected OverlayItem createItem(int arg0) {
		return mOverlays.get(arg0);
	}

	@Override
	public int size() {
		return mOverlays.size();
	}

	@Override
	protected boolean onTap(int index) {
		OverlayItem overlayItem = mOverlays.get(index);
		popupWindow.show(popupParent, 0, 0);
		return false;
	}
}
